package com.lsf.dunlian.activity;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.lsf.dunlian.Myappliction;
import com.lsf.dunlian.R;
import com.lsf.dunlian.adapter.FileRecyclerViewAdapter;
import com.lsf.dunlian.config.Urls;
import com.lsf.dunlian.databinding.ActivityFileListBinding;
import com.lsf.dunlian.entity.FileEntity;
import com.lsf.dunlian.entity.UploadFileEntity;
import com.lsf.dunlian.utils.audio.ContentUriUtil;
import com.lsf.dunlian.utils.audio.FileSizeUtil;
import com.lsf.dunlian.utils.audio.UploadImage;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class FileListActivity extends Activity {
    private ActivityFileListBinding binding;
    private FileRecyclerViewAdapter fileRecyclerViewAdapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseUtils.setStatusBar(this);
        binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_file_list, null, false);
        setContentView(binding.getRoot());
        init();
    }

    private void init() {
        binding.back.setOnClickListener(v -> finish());
        binding.xzwj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                // 所有类型
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                try {
                    startActivityForResult(Intent.createChooser(intent, "请选择文件"), 1);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(FileListActivity.this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
                }
            }
        });

        fileRecyclerViewAdapter = new FileRecyclerViewAdapter(Myappliction.fileEntityList, this);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(fileRecyclerViewAdapter);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            //Get the Uri of the selected file
            Uri uri = data.getData();
            if (null != uri) {
                String path = ContentUriUtil.getPath(this, uri);
                Log.i("filepath", " = " + path);
                uploadFile(path);
            }
        }
    }


    public void uploadFile(String filePath) {
        File file = new File(filePath);
        String fileName = file.getName();

        try {
            long fileSize = FileSizeUtil.getFileSize(file);
            Myappliction.fileEntityList.add(new FileEntity(fileName,fileSize));
            fileRecyclerViewAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }


        String names = fileName.substring(fileName.length() - 4);
        HashMap<String, String> hashMap = new HashMap();
        //上传文件
        new UploadImage().uploadForm("img", file, names, Urls.UPLOADFILE, (progress, sum) ->
        {
            for (int i = 0; i <Myappliction.fileEntityList.size() ; i++) {
                if (Myappliction.fileEntityList.get(i).name.equals(fileName)){
                    Myappliction.fileEntityList.get(i).progress=progress;
                    runOnUiThread(() -> fileRecyclerViewAdapter.notifyDataSetChanged());
                    break;
                }
            }
        }, (int state, String json) -> {
            UploadFileEntity entity = new Gson().fromJson(json,UploadFileEntity.class);
            if (entity.code==200 && StringUtils.isNotEmpty(entity.data)) {
                for (int i = 0; i < Myappliction.fileEntityList.size(); i++) {
                    if (Myappliction.fileEntityList.get(i).name.equals(fileName)) {
                        Myappliction.fileEntityList.get(i).src = entity.data;
                        runOnUiThread(() -> fileRecyclerViewAdapter.notifyDataSetChanged());
                        break;
                    }
                }
            }
        }, hashMap);
    }
}
